package com.quanyan.vote.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.vote.cache.MyRedisTemplate;
import com.quanyan.vote.constans.VoteConstans;
import com.quanyan.vote.entity.db.*;
import com.quanyan.vote.entity.vo.req.ReqVoteDetail;
import com.quanyan.vote.entity.vo.req.ReqVoteFirstPage;
import com.quanyan.vote.entity.vo.req.ReqVoteToExpert;
import com.quanyan.vote.entity.vo.resp.RespExactlyExpertDetail;
import com.quanyan.vote.entity.vo.resp.RespVoteFirstPage;
import com.quanyan.vote.mapper.TbVoteExpertMapper;
import com.quanyan.vote.mapper.TbVoteMapper;
import com.quanyan.vote.mapper.TbVoteRuleMapper;
import com.quanyan.vote.mapper.TbVoteVoterMapper;
import com.quanyan.vote.service.TbVoteExpertService;
import com.quanyan.vote.utils.VoteEnum;
import com.quanyan.vote.utils.VoteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by Administrator on 2016/7/21.
 */
@Service("tbVoteExpertServiceImpl")
public class TbVoteExpertServiceImpl implements TbVoteExpertService{

    private static final Logger LOGGER = LoggerFactory.getLogger(TbVoteExpertServiceImpl.class);

    /**
     * 投票规则
     */
    @Autowired
    private TbVoteRuleMapper tbVoteRuleMapper;

    /**
     * 达人
     */
    @Autowired
    private TbVoteExpertMapper tbVoteExpertMapper;

    /**
     * 被投票人
     */
    @Autowired
    private TbVoteVoterMapper tbVoteVoterMapper;

    /**
     * 查看排名
     */
    @Autowired
    private TbVoteMapper tbVoteMapper;

    /**
     * 是否允许投票
     * @return
     */
    private int isSuccess(){
        LOGGER.debug("--------check----isSuccess---to----vote---------");
        TbVoteRule tbVoteRule =tbVoteRuleMapper.selectByPrimaryKey(VoteConstans.VOTE_RULE_ID);
        int isAccess=VoteUtil.compareDate(tbVoteRule.getTpStartTime(),tbVoteRule.getTpEndTime(),new Date());
        //0--未到投票时间，1--投票时间，2--投票活动已结束
        LOGGER.debug("-------是否可以投票------->>>>>"+isAccess);
        return isAccess;
    }

    /**
     * 是否投过票了，false没投过票，true投过票了
     * @return
     */
    private boolean isVoteSuccess(String openId){
        //判断该openid今天是否已投票
        Map<String,Object> map=new HashMap<>();
        map.put("openId",openId);
        return tbVoteMapper.queryCountVoteToday(map)>0;//只要今天手机号投过票，则不允许投票
    }

    /**
     * 同一个ip票数超过五次为true,否则false
     * @param ip
     * @return
     */
    private boolean isOverFiveIPAddress(String ip){
        TbVoteVoterExample tbVoteVoterIp=new TbVoteVoterExample();
        tbVoteVoterIp.createCriteria().andVoteDateEqualTo(new Date()).andIpAddressEqualTo(ip);
        int ipCount=tbVoteVoterMapper.countByExample(tbVoteVoterIp);
        LOGGER.debug("------同一个ip投票次数-------->>>>"+ipCount);
        return ipCount>=VoteConstans.IP_COUNT_DAY;
    }

    /**
     * 投票首页
     * 说明：根据id精确查找,输入id查找获得全国排名，
     * @return
     */
    @Override
    public APIResponse<Map<String,Object>> voteFirstPage(ReqVoteFirstPage reqVoteFirstPage) {
        PageObj<List<RespVoteFirstPage>> result=null;
        Map<String,Object> map=new HashMap<>();
        if (null != reqVoteFirstPage.getId()){//用户通过编号精确查找
            map.put("id",reqVoteFirstPage.getId());
            map.put("city",reqVoteFirstPage.getCity());
            RespVoteFirstPage respVoteFirstPage=tbVoteMapper.queryFirstPageById(map);
            if(respVoteFirstPage==null){//精确查找有该达人
                return APIResponse.returnFail("没有该记录");
            }
            List<RespVoteFirstPage> respVoteFirstPages=new ArrayList<RespVoteFirstPage>();
            respVoteFirstPages.add(respVoteFirstPage);
            result=PageObj.create(1,0,1,respVoteFirstPages);
        }else{
            map.put("pageNum",reqVoteFirstPage.getPageNum() * reqVoteFirstPage.getPageSize());
            map.put("pageSize",reqVoteFirstPage.getPageSize());
            map.put("name",reqVoteFirstPage.getName());
            map.put("city",reqVoteFirstPage.getCity());
            Integer totalCount=null;
            if (!StringUtil.isBlankOrNull(reqVoteFirstPage.getName()) || null !=reqVoteFirstPage.getCity()){//有搜索条件
                totalCount=tbVoteMapper.countVoteExpert(map);
            }else{//没有搜索条件
                TbVoteExpertExample tbVoteExpertExample=new TbVoteExpertExample();
                totalCount=tbVoteExpertMapper.countByExample(tbVoteExpertExample);
            }
            if(isSuccess()==VoteConstans.VOTE_TIME || isSuccess()==VoteConstans.VOTE_TIME_OUT){//可以投票了,根据票数排序,否则根据编号排序
                map.put("orderByVoteCount","vote_count");
            }
            List<RespVoteFirstPage> respVoteFirstPageList=tbVoteMapper.queryVoteExpertList(map);
            if (respVoteFirstPageList.size()==0){
                return APIResponse.returnFail("没有该记录");
            }
            result=PageObj.create(totalCount,reqVoteFirstPage.getPageNum(),reqVoteFirstPage.getPageSize(),respVoteFirstPageList);
        }
        map.clear();
        map.put("data",result);
        //投票时间，只投一票，ip
        //0--未到投票时间，2--投票活动结束，3--今日已投过票了，5--同一个ip超过五次
        if (isSuccess()==VoteConstans.VOTE_TIME_IN){//未到投票时间
            map.put("isVote",false);
            return APIResponse.returnSuccess(map,VoteEnum.VOTE_TIME_IN);
        }else if(isSuccess()==VoteConstans.VOTE_TIME_OUT){//投票活动结束
            map.put("isVote",false);
            return APIResponse.returnSuccess(map,VoteEnum.VOTE_TIME_OUT);
        }else if(isVoteSuccess(reqVoteFirstPage.getD8bd9db46973e30cfa3413e9d78f6b97())){//今天已经投票了
            map.put("isVote",false);
            return APIResponse.returnSuccess(map,VoteEnum.YSE_VOTE_TODAY);
        }else if(isOverFiveIPAddress(reqVoteFirstPage.getIp())){//同一个ip超过五次
            map.put("isVote",false);
            return APIResponse.returnSuccess(map,VoteEnum.IP_VOTE_OVER_FIVE);
        }else{
            map.put("isVote",true);
            return APIResponse.returnSuccess(map);
        }

    }

    /**
     * 查看达人投票详情
     * @param reqVoteDetail
     * @return
     */
    @Override
    public APIResponse<RespExactlyExpertDetail> expertDetail(ReqVoteDetail reqVoteDetail) {
        //判断投票活动是否开始
        if (isSuccess()==VoteConstans.VOTE_TIME_IN){//未到投票时间
            TbVoteExpert tbVoteExpert=tbVoteExpertMapper.selectByPrimaryKey(reqVoteDetail.getExpertId());
            RespExactlyExpertDetail respExpertDetail=new RespExactlyExpertDetail(tbVoteExpert.getId(),0,0,tbVoteExpert.getName(),tbVoteExpert.getCity(),tbVoteExpert.getSport(),tbVoteExpert.getPhotoUrl(),0,false);//不允许投票
            return APIResponse.returnSuccess(respExpertDetail,VoteEnum.VOTE_TIME_IN);
        }else{
            //查询排名
            Map<String,Object> paramMap=new HashMap<>();
            paramMap.put("id",reqVoteDetail.getExpertId());
            paramMap.put("city",reqVoteDetail.getCity());
            RespExactlyExpertDetail respVoteCity = tbVoteMapper.queryExpertDetail(paramMap);
            if(null ==respVoteCity){//达人表没数据
                return APIResponse.returnSuccess();
            }
            if(isSuccess()==VoteConstans.VOTE_TIME_OUT){//投票活动结束
                respVoteCity.setIsVote(false);//不允许投票
                return APIResponse.returnSuccess(respVoteCity,VoteEnum.VOTE_TIME_OUT);
            }else if(isVoteSuccess(reqVoteDetail.getD8bd9db46973e30cfa3413e9d78f6b97())){//今天已经投票了
                respVoteCity.setIsVote(false);//不允许投票
                return APIResponse.returnSuccess(respVoteCity,VoteEnum.YSE_VOTE_TODAY);
            }else if(isOverFiveIPAddress(reqVoteDetail.getIp())){//同一个ip超过五次
                respVoteCity.setIsVote(false);//不允许投票
                return APIResponse.returnSuccess(respVoteCity,VoteEnum.IP_VOTE_OVER_FIVE);
            }else{
                respVoteCity.setIsVote(true);
                return APIResponse.returnSuccess(respVoteCity);
            }
        }
    }

    /**
     * 投票给达人
     * @param reqVoteToExpert
     * @return
     */
    @Override
    @Transactional
    public APIResponse voteToExpert(ReqVoteToExpert reqVoteToExpert) {
        //是否在投票时间内
        if (isSuccess()!=VoteConstans.VOTE_TIME){//还没有开始投票
            return APIResponse.returnFail(VoteEnum.VOTE_TIME_IN);
        }
//        防止刷票
//        查看openid今天是否允许投票
        if (isVoteSuccess(reqVoteToExpert.getD8bd9db46973e30cfa3413e9d78f6b97())){//openid今天投过票
            return APIResponse.returnFail(VoteEnum.YSE_VOTE_TODAY);
        }else if(isOverFiveIPAddress(reqVoteToExpert.getIp())){//查看ip是否投票超过5次
            return APIResponse.returnFail(VoteEnum.IP_VOTE_OVER_FIVE);
        }else{
            //插入新数据
            TbVoteVoter tbVoteVoter=new TbVoteVoter();
            tbVoteVoter.setExpertId(reqVoteToExpert.getId());
            tbVoteVoter.setOpenId(reqVoteToExpert.getD8bd9db46973e30cfa3413e9d78f6b97());
            tbVoteVoter.setIpAddress(reqVoteToExpert.getIp());
            tbVoteVoter.setVoteNum((byte) 1);
            tbVoteVoter.setVoteDate(new Date());
            tbVoteVoter.setVoteDateDetail(new Date());
            tbVoteVoter.setDeviceMsg(reqVoteToExpert.getDeviceMsg());//设备信息
            tbVoteVoterMapper.insertSelective(tbVoteVoter);
            //跟新达人票数
            int updateSucc=tbVoteMapper.updateExpertVoteNum(reqVoteToExpert.getId());
            return updateSucc>0?APIResponse.returnSuccess():APIResponse.returnFail("跟新达人票数失败");
        }
    }

}
